﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WSManager.Model;

namespace WSManager.Wpf.ArticleEditor
{
    static class ArticleEditorManager
    {
        static Action<Article> _callBack;
        static Article _actualyEditing;
        static EditorViewModel _editorVm;
        static Web _context;

        static public Article BeginCreateArticle(Action<Article> callBack, Web context)
        {
            var a = new Article() { Name = "New Article", Categories = new Category[0] };
            BeginEditArticle(a, callBack, context);
            return a;
        }

        static public void BeginEditArticle(Article a, Action<Article> callBack, Web context)
        {
            if (a == null) throw new ArgumentNullException("a");
            if (context == null) throw new ArgumentNullException("context");
            _actualyEditing = a.Repair();
            _context = context;
            var editWindow = new ArticleEditor();
            editWindow.Show();
            _callBack = callBack;
        }

        static internal Article RegisterEditorVm(EditorViewModel vm)
        {
            if (vm == null) throw new ArgumentNullException("vm");
            if (_editorVm != null) throw new InvalidOperationException("can not edit multiple articles");
            _editorVm = vm;
            return _actualyEditing;
        }

        static internal Web GetWebContext(EditorViewModel vm)
        {
            if (vm == null) throw new ArgumentNullException("vm");
            if (_editorVm == null) throw new InvalidOperationException("EditorViewModel must be registered");
            if (_editorVm != vm) throw new InvalidOperationException("Another editor is editing");
            return _context;
        }

        static internal void SaveArticle(EditorViewModel vm)
        {
            DeregisterEditorVm(vm);
            _callBack(vm.Article);
        }

        static internal void DeregisterEditorVm(EditorViewModel vm)
        {
            if (vm == null) throw new ArgumentNullException("vm");
            if (_editorVm != vm) throw new InvalidOperationException();
            _editorVm = null;
        }

        static internal bool IsRegistered(EditorViewModel vm)
        {
            return vm == _editorVm;
        }
    }
}
